package com.lxy.phonebook.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxy.phonebook.constant.SystemConstant;
import com.lxy.phonebook.entity.Admin;
import com.lxy.phonebook.service.AdminService;
import com.lxy.phonebook.utils.JwtUtils;
import com.lxy.phonebook.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("Admin")
public class AdminController {

    @Autowired
    AdminService adminService;

    @PostMapping("/login")
    public R login(@RequestBody Admin admin){
        System.out.println(admin);
        try {
            //验证用户名和密码
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userName",admin.getUsername());
            queryWrapper.eq("password",admin.getPassword());
            Admin an = adminService.getOne(queryWrapper);
            if(an == null){
                return R.error("用户名或者密码错误！");
            }
            //return R.ok("登陆成功！");
            //步骤：1.生成token  2.把token保存到localStorage中 3.下次请求携带token  生成token 给个id，名字，时间 SystemConstant.JWT_TTL（1个小时）
            String token = JwtUtils.createJWT("1001", admin.getUsername(), SystemConstant.JWT_TTL);
            return R.ok(token);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务端异常！");
        }
    }
}
